import React from 'react';
import {connect} from "react-redux";
import {Button, Input, Select, Popover, Badge, message} from 'antd';
import SlideFrame from "components/slide-frame";
import menuRoute from "routes/menuRoute";
import {messages} from "share/common";
import baseService from 'share/base.service'
import taxCodeServer from 'containers/finance-setting/tax-code/tax-code-server';
import errorMessage from "share/errorMessage";
import UpdateRule from "containers/finance-setting/tax-code/tax-code/update-rule"
import ListSelector from 'components/list-selector';
import chooserData from 'share/chooserData'
import ResizeTable from 'components/resize-table'
const Search = Input.Search;

class TaxCode extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      columns: [
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: "index",
          width: "10%",
          render: (value, record, index) => this.state.pageSize * this.state.page + index + 1
        },
        {
          title: messages('finance-setting.key72'/*规则名称*/), dataIndex: "ruleName", width: "20%", render: value => {
            return <Popover content={value}>{value}</Popover>
          }
        },
        {
          title: messages('finance-setting.key94'/*分配公司*/), dataIndex: "taxCodeCompanyEntityDTOS", width: "30%", render: (value) => {
            let array = [];
            value && value.length > 0 && value.map(item => {
              item && array.push(item.companyName);
            })
            return <Popover content={array.join(",")}>{array.join(",")}</Popover>
          }
        },
        {
          title: messages('finance-setting.key141'/*规则状态*/), dataIndex: "enabled", width: "20%", render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: "operate",
          width: "20%",
          render: (text, record) => (
            <div>
              <a onClick={(e) => this.clickEdit(record)} disabled={!this.props.tenantMode}>
                {/*编辑*/}
                {messages("common.edit")}
              </a>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <a onClick={(e) => this.clickDetails(record)}>
                {/*详情*/}
                {messages("common.detail")}
              </a>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <a onClick={(e) => this.clickAllotCompany(record)} disabled={!this.props.tenantMode}> {messages('finance-setting.key94'/*分配公司*/)}
              </a>
            </div>)
        }],
      showCompanyModal: false,//显示批量分配公司
      showRuleInfoModal: false,//显示规则详情
      ruleInfo: {},//单个规则信息
      dataList: [],//规则list信息
      selectedRowKeys: [],//选中的行，用于启用或者禁用
      setOfBooksOption: [],//账套集合
      companySelectItem: chooserData['allotSetOfBookCompany'],
      currentSetOfBooksId: null,//单个规则信息, //当前默认or选中的账套
      currentSelectedCompanyData: [],
      searchParam:''
    }
  }

  componentDidMount() {
    this.getSetOfBooks();
  }

  //初始化选择账套的options
  getSetOfBooks = () => {
    let {currentSetOfBooksId, ruleInfo, currentSetOfBooksName} = this.state;
    baseService.getSetOfBooksByTenant().then(res => {
      ruleInfo.setOfBooksId = res.data[0].id;
      ruleInfo.setOfBooksName = res.data[0].setOfBooksName;
      if (this.props.location.state && this.props.location.state.setOfBooksId) {
        currentSetOfBooksId = this.props.location.state.setOfBooksId;
      }
      if (currentSetOfBooksId) {
        res.data.map(item => {
          if (item.id + '' === currentSetOfBooksId + '') {
            currentSetOfBooksName = item.setOfBooksName;
          }
        })
      }
      this.setState({
        setOfBooksOption: res.data,
        currentSetOfBooksId: currentSetOfBooksId || res.data[0].id,
        currentSetOfBooksName: currentSetOfBooksName || res.data[0].setOfBooksName
      }, () => {
        this.getList();
      })
    })
  };
  //选中指定账套
  onSelectSetOfBook = (value) => {
    let {setOfBooksOption} = this.state;
    let {currentSetOfBooksName} = this.state;
    setOfBooksOption.map(item => {
      if (item.id === value) {
        currentSetOfBooksName = item.setOfBooksName;
      }
    })
    this.setState({
      currentSetOfBooksId: value,
      currentSetOfBooksName
    }, () => {
      this.getList();
    });
  };
  //点击编辑
  clickEdit = (record) => {
    this.setState({
      showRuleInfoModal: true,
      ruleInfo: record
    })
  };
  //点击详情
  clickDetails = (record) => {
    this.context.router.push({
      pathname: menuRoute.getRouteItem('invoice-type').url.replace(':ruleId', record.id),
      state: {ruleInfo: record}
    })
  };
  //新建编码规则
  clickCreateCodeRule = () => {
    let {currentSetOfBooksId, currentSetOfBooksName} = this.state;
    let ruleInfo = {
      setOfBooksId: currentSetOfBooksId,
      setOfBooksName: currentSetOfBooksName
    }
    this.setState({
      showRuleInfoModal: true, ruleInfo: ruleInfo
    })
  };
  //批量启用、禁用
  clickEnable = (enable) => {
    let {selectedRowKeys, dataList} = this.state;
    this.setState({loading:true})
    taxCodeServer.enableTaxCode(selectedRowKeys, enable).then(res => {
      this.setState({loading:false})
      dataList.map(item => {
        if (~selectedRowKeys.indexOf(item.id)) {
          item.enabled = enable;
        }
      })
      this.setState({selectedRowKeys: [], dataList});
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      this.setState({loading:false})
      errorMessage(e.response);
    })
  }
  //模糊查询
  searchList = (searchParam) => {
    let {pagination}=this.state;
    pagination.page=0;
    pagination.current=0;
    this.setState({
      page: 0,
      pagination,
      searchParam
    },()=>{
      this.getList();
    })
  }
  //获取规则列表
  getList = () => {
    let {currentSetOfBooksId, companyId, page, pageSize, searchParam} = this.state;
    let {company, tenantMode} = this.props;
    if (tenantMode) {
      companyId = company.companyId;
    }
    this.setState({loading: true})
    taxCodeServer.queryTaxCodeRulePage(currentSetOfBooksId, companyId, page, pageSize, searchParam).then(res => {
      let {pagination} = this.state;
      pagination.total = res.data.total;
      this.setState({
        dataList: res.data.rows,
        loading: false,
        pagination
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({
        dataList: [],
        loading: false
      })
    });
  };
  //表单分页、排序处理
  handleTableChange = (pagination) => {
    let page = pagination.current;
    this.setState({
      page: page - 1,
      pagination
    }, () => {
      this.getList();
    })
  }
  //关闭弹框
  closeRuleInfoModal = () => {
    this.setState({
      showRuleInfoModal: false
    })
  }
  //处理列表动态更新.若存在则修改，若不存在则添加
  handleListUpdate = (ruleInfo) => {
    let {dataList, pagination} = this.state;
    let ifExist = false;
    dataList.map(item => {
      if (item.id === ruleInfo.id) {
        ifExist = true;
        item = ruleInfo;
      }
    })
    if (!ifExist) {
      pagination.total += 1;
      dataList.unshift(ruleInfo);
    }
    this.setState({dataList, pagination})
  }
  //规则分配公司确认
  handleAllotCompanyOk = (result) => {
    let {ruleInfo, dataList} = this.state;
    let companyIds = [];
    let taxCodeCompanyEntityDTOS = [];
    result.result.length > 0 && result.result.map(item => {
      companyIds.push(item.id);
      if (!item.name) {
        ruleInfo.taxCodeCompanyEntityDTOS && ruleInfo.taxCodeCompanyEntityDTOS.map(company => {
          if(item.id === company.companyId){
            item.name = company.companyName;
          }
        })
      }
      taxCodeCompanyEntityDTOS.push(
        {
          companyId: item.id,
          companyName: item.name,
          enable: true
        }
      )
    })
    this.setState({loading: true})
    taxCodeServer.allotCompanyToTaxCode(ruleInfo.id, companyIds).then(res => {
      message.success(messages('common.operate.success')/*操作成功*/);
      let {dataList} = this.state;
      dataList.map(item => {
        if (item.id === ruleInfo.id) {
          item.taxCodeCompanyEntityDTOS = taxCodeCompanyEntityDTOS;
        }
      })
      this.setState({showCompanyModal: false, dataList, loading: false})
    }).catch(e => {
      this.setState({showCompanyModal: false, loading: false})
      errorMessage(e.response)
    })
  }
  //规则分配公司取消
  handleAllotCompanyCancel = () => {
    this.setState({showCompanyModal: false})
  }
  //点击分配公司
  clickAllotCompany = (record) => {
    let currentSelectedCompanyData = [];

    record.taxCodeCompanyEntityDTOS && record.taxCodeCompanyEntityDTOS.length > 0 && record.taxCodeCompanyEntityDTOS.map(item => {
      currentSelectedCompanyData.push({id: item.companyId})
    })
    this.setState({currentSelectedCompanyData, showCompanyModal: true, ruleInfo: record})
  }
  //选中的行存储
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys})
  }

  render() {
    const {tenantMode} = this.props;
    const {columns, pagination, loading, dataList, showRuleInfoModal, showCompanyModal, setOfBooksOption, currentSetOfBooksId, ruleInfo, companySelectItem, currentSelectedCompanyData, selectedRowKeys} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <div style={{marginBottom: 40}}>
          {tenantMode && currentSetOfBooksId && <div>{messages('finance-setting.key147'/*账套：*/)}
            <Select
              getPopupContainer={triggerNode => triggerNode.parentNode}
              style={{width: 200}}
              placeholder={messages("common.please.select")/*请选择账套*/}
              onSelect={this.onSelectSetOfBook}
              defaultValue={currentSetOfBooksId}
            >
              {setOfBooksOption && setOfBooksOption.length > 0 && setOfBooksOption.map(item => (
                <Option key={item.id} value={item.id}>{item.setOfBooksName}</Option>
              ))}
            </Select>
          </div>}
        </div>
        {tenantMode && <div style={{marginBottom: 20}}>
          <Button type="primary" style={{marginRight: 60}} onClick={this.clickCreateCodeRule}>{messages('finance-setting.key148'/*新建编码规则*/)}</Button>
          <Button size="small" loading={loading} disabled={selectedRowKeys.length > 0 ? false : true}
                  onClick={() => this.clickEnable(true)}>{messages('common.status.enable')/*启用*/}</Button> &nbsp;&nbsp;
          <Button size="small" loading={loading} disabled={selectedRowKeys.length > 0 ? false : true}
                  onClick={() => this.clickEnable(false)}>{messages('common.status.disable')/*禁用*/}</Button>
          <Search
            placeholder={messages('finance-setting.key149'/*请输入规则名称*/)}
            enterButton={true}
            onSearch={(value) => this.searchList(value)}
            style={{width: 200, float: "right"}}
          />
        </div>}
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          {/* 共total条数据 */}
        </div>
        <ResizeTable
          rowKey="id"
          rowSelection={tenantMode ? rowSelection : undefined}
          columns={columns}
          dataSource={dataList}
          onChange={this.handleTableChange}
          pagination={pagination}
          loading={loading}
          size="middle"
          bordered
        />
        {/*侧边栏创建、编辑*/}
        {/*       <Drawer
        title={ruleInfo.id ? "编辑规则" : "新建规则"}
        width={620}
        closable={true}
        onClose={this.closeRuleInfoModal}
        visible={showRuleInfoModal}>
        <UpdateRule updateListRuleInfo={this.handleListUpdate} onClose={this.closeRuleInfoModal} ruleInfo={ruleInfo}/>
      </Drawer>*/}
        <SlideFrame show={showRuleInfoModal}
                    title={ruleInfo.id ? messages('finance-setting.key81'/*编辑规则*/) : messages('finance-setting.key84'/*新建规则*/)}
                    hasFooter={false}
                    params={{
                      ruleInfo: ruleInfo,
                      updateListRuleInfo: this.handleListUpdate,
                      onClose: this.closeRuleInfoModal
                    }}
          /*content={<UpdateRule updateListRuleInfo={this.handleListUpdate} onClose={this.closeRuleInfoModal} ruleInfo={ruleInfo}/>}*/
                    content={UpdateRule}
                    onClose={this.closeRuleInfoModal}
                    afterClose={this.closeRuleInfoModal}
                    width="800px"/>
        {/*分配公司Modal*/}
        <ListSelector
          visible={showCompanyModal}
          selectedData={currentSelectedCompanyData}
          onOk={this.handleAllotCompanyOk}
          onCancel={this.handleAllotCompanyCancel}
          extraParams={{setOfBooksId: currentSetOfBooksId}}
          selectorItem={companySelectItem}
        />
      </div>
    )

  }

}

TaxCode.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(TaxCode);
